package web.action.com;


import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Maps;
import com.joint.base.entity.Company;
import com.joint.base.entity.Department;
import com.joint.base.entity.Power;
import com.joint.base.entity.Users;
import com.joint.base.service.*;
import com.joint.base.util.excel.ExportExcel;
import com.joint.base.util.excel.ImportExcel;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import web.action.BaseAdminAction;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by amin on 2014/11/14.
 */
@ParentPackage("com")
public class AjaxImportAction extends BaseAdminAction {
    private File Filedata;
    private String Filename;
    private String FiledataFileName;
    private String FiledataContentType;
    private String[] Upload;
    @Resource
    private UsersService usersService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postServer;
    @Resource
    private CompanyService companyService;
    @Resource
    private PowerService powerService;
    private String cvsname;

    private static Logger log = LoggerFactory.getLogger(AjaxImportAction.class);
    public String exportFile(){
        try{
            String fileName = "用户数据" + DateFormatUtils.format(new Date(), "yyyy-MM-dd kk-mm-ss") + ".xlsx";
            pager=new Pager();
            pager = usersService.findByPagerAndStates(pager,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
            List<Users> usersList= (List<Users>) pager.getList();
            new ExportExcel("用户数据",Users.class).setDataList(usersList).write(getTheResponse(),fileName).dispose();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    //导出职权信息
    public String exportPowerFile(){
        try{
            String fileName = "职权数据" + DateFormatUtils.format(new Date(), "yyyy-MM-dd kk-mm-ss") + ".xlsx";
            pager=new Pager();
            pager = powerService.findByPagerAndStates(pager,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
            List<Power> powerList= (List<Power>) pager.getList();
            new ExportExcel("职权数据",Power.class).setDataList(powerList).write(getTheResponse(),fileName).dispose();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    //导出部门信息
    public String exportFileDept(){
        try{
            String fileName = "部门数据" + DateFormatUtils.format(new Date(), "yyyy-MM-dd kk-mm-ss") + ".xlsx";
            pager = new Pager();
            pager.setOrderBy("no");
            pager.setOrderType(BaseEnum.OrderType.asc);
            pager = departmentService.findByPagerAndStates(pager, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
            List<Department> deptList= (List<Department>) pager.getList();
            new ExportExcel("部门数据",Department.class).setDataList(deptList).write(getTheResponse(),fileName).dispose();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public String downTemplate(){
        try {
            String fileName = "用户数据导入模板.xlsx";
//            new ExportExcel("用户数据", Users.class,2).write(getResponse(), fileName).dispose();
            return null;
        } catch (Exception ex) {
            log.info("用户数据导入模板下载 error: " + ex.toString());
        }
        return null;
    }

    public String downTemplatePower(){
        try {
            String fileName = "职权数据导入模板.xlsx";
//            new ExportExcel("职权数据", Users.class,2).write(getResponse(), fileName).dispose();
            return null;
        } catch (Exception ex) {
            log.info("职权数据导入模板下载 error: " + ex.toString());
        }
        return null;
    }

    //部门数据导入模板
    public String downTemplateDept(){
        try {
            String fileName = "部门数据导入模板.xlsx";
        //    new ExportExcel("部门数据", Department.class,2).write(getResponse(), fileName).dispose();
            return null;
        } catch (Exception ex) {
            LogUtil.info("部门数据导入模板下载 error: " + ex.toString());
        }
        return null;
    }

    public String upload(){
        try {
            ImportExcel ei = new ImportExcel(Filename,Filedata, 1, 0);
            Company com=usersService.getCompanyByUser();
            Users create=usersService.getLoginInfo();
            Map<String,Object> rmap;
            Department depart;
            Company coms;
            if(StringUtils.isNotEmpty(cvsname)){
                rmap= Maps.newHashMap();
                rmap.put("state", BaseEnum.StateEnum.Enable);
                if(StringUtils.equals("user",cvsname)){
                    List<Users> list = ei.getDataList(Users.class);
                    for (Users user : list){
                        if(usersService.getUsersByEmail(user.getEmail())!=null) continue;
                        user.setState(BaseEnum.StateEnum.Enable);
                        user.setCompany(com);
                        user.setCreater(create);
                        String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
                        user.setPassword(usersService.encodedPassword(user.getEmail(),"pass",salt));
                        usersService.save(user);
                    }
                }
                if(StringUtils.equals("depart",cvsname)){
                    List<Department> list = ei.getDataList(Department.class);
                    System.out.println("{数组}" + list.size());
                    for (Department department : list){
                        System.out.println("{公司名称}"+department.getCompany());
                        rmap.put("name",department.getCompany().getName());//根据名称找公司
                        pager=companyService.findByPagerAndCompany(new Pager(),null,com,rmap);
                        if(pager!=null && pager.getList().size()>0){
                            continue;
                        }else{
                            coms=new Company();
                            coms.setCreater(create);
                            coms.setState(BaseEnum.StateEnum.Enable);
                            coms.setName(department.getCompany().getName());
                            companyService.save(coms);
                        }

                        rmap.put("name",department.getName());
                        pager=departmentService.findByPagerAndCompany(new Pager(),null,com,rmap);//根据名称找部门
                        if(pager!=null && pager.getList().size()>0){
                            continue;
                        }else{
                            depart=new Department();
                            depart.setState(BaseEnum.StateEnum.Enable);
                            depart.setCreater(create);
                            depart.setCompany(coms);
                        }
                        departmentService.save(depart);
                    }
                }
            }

            return  ajaxHtmlCallback("200","上传成功","操作状态");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }



    public String dialog(){
        return "dialog";
    }
    public String powerDialog(){
        return "powerDialog";
    }
    //导入部门对话框
    public String dialogDept(){
        return "dialogDept";
    }

    public String[] getUpload() {
        return Upload;
    }

    public void setUpload(String[] upload) {
        Upload = upload;
    }

    public String getFiledataContentType() {
        return FiledataContentType;
    }

    public void setFiledataContentType(String filedataContentType) {
        FiledataContentType = filedataContentType;
    }

    public String getFiledataFileName() {
        return FiledataFileName;
    }

    public void setFiledataFileName(String filedataFileName) {
        FiledataFileName = filedataFileName;
    }

    public String getFilename() {
        return Filename;
    }

    public void setFilename(String filename) {
        Filename = filename;
    }

    public File getFiledata() {
        return Filedata;
    }

    public void setFiledata(File filedata) {
        Filedata = filedata;
    }

    public String getCvsname() {
        return cvsname;
    }

    public void setCvsname(String cvsname) {
        this.cvsname = cvsname;
    }
}